#!/bin/sh

#
# UBUNTU NOTE
# -----------
# 1. When downgrading (say from 2.3.0 to 2.2.0) then prerm of 2.3.0 is run
#    but postinst of 2.2.0 is run. The prerm is invoked with "upgrade 2.2.0"
#    argument and postinst is invoked with "configure 2.3.0" argument.
# 2. When upgrading (say from 2.2.0 to 2.3.0) then prerm of 2.2.0 is run
#    but postinst of 2.3.0 is run. The prerm is invoked with "upgrade 2.3.0"
#    argument and postinst is invoked with "configure 2.2.0" argument.
# 3. When re-installing (say from 2.2.0 to 2.2.0) then prerm of 2.2.0 is run
#    and postinst of 2.2.0 is run. The prerm is invoked with "upgrade 2.2.0"
#    argument and postinst is invoked with "configure 2.2.0" argument.
#
# RHEL/CentOS NOTE
# ----------------
# 1. When downgrading (say from 2.3.0 to 2.2.0) then oddly postinst of 2.2.0
#    is run first followed by prerm of 2.3.0 run. The postinst is invoked with
#    "2" and prerm is invoked with "1".
# 2. When upgrading (say from 2.2.0 to 2.3.0) then prerm of 2.2.0 is NOT run
#    but postinst of 2.3.0 is run. The postinst is invoked with "2" argument.
# 3. When re-installing (say from 2.2.0 to 2.2.0) then prerm is NOT run but
#    and postinst of 2.2.0 is run. The postinst is invoked with "2" argument.

# In the case of upgrade, downgrade or re-install we would like to preserve the
# configuration of the components and hence we want to handle the configuration
# in postinst script.

nm /opt/xilinx/xrt/lib/libaws_mpd_plugin.so |grep 'fpga_mgmt' > /dev/null 2>&1
if [ $? -eq 1 ]; then
    echo "Unloading old AWS Linux kernel modules"
    modprobe -r awsmgmt

    echo "Unregistering AWS Linux kernel module sources @XRT_VERSION_STRING@ from dkms"
    dkms remove -m xrt-aws -v @XRT_VERSION_STRING@ --all
    find /lib/modules -type f -name awsmgmt.ko -delete
    find /lib/modules -type f -name awsmgmt.ko.kz -delete
    depmod -A

    rm -f /etc/udev/rules.d/10-awsmgmt.rules
fi

#In case prerm is called after postinst on centos, make sure not to stop mpd
lsb_release -si | grep -Eq "^RedHat|^CentOS"
if [ $? -eq 0 ] && [ $1 -ge 1 ]; then
    echo "Cleanup is skipped for package upgrade/downgrade/re-install on RHEL/CentOS"
    exit 0
fi

echo "Remove mpd plugin"
rm -rf /opt/xilinx/xrt/lib/libmpd_plugin.so > /dev/null 2>&1
systemctl disable mpd > /dev/null 2>&1
systemctl stop mpd > /dev/null 2>&1

exit 0
